//启动聊天的服务端程序
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
//用户列表
var users = []
server.listen(3001,()=>{
	console.log('服务器启动成功：3001端口')
})

//express 处理静态资源
// 把public目录设置weight静态资源目录
app.use(require('express').static('public'))
// 设置允许跨域访问该服务
app.all('*', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  res.header('Access-Control-Allow-Headers', 'mytoken');
  next();
});
app.get('/',function(req,res){
	// res.sendFile(__dirname + '/index.html')
	res.header("Access-Control-Allow-Origin", "*");
	res.redirect('/index.html')
})

io.on('connection',function(socket){
	
	socket.on('login',data=>{
		// console.log(data)
		let user = users.find(item => item.username === data.username )
		if(user){
			//用户存在
			socket.emit('loginError',{msg:'登录失败'})
			// console.log('登录失败')
		}else{
			users.push(data)
			socket.emit('loginSuccess',data)
			// console.log('登录成功');
			//告诉所有用户，有用户加入到聊天室
			io.emit('addUser',data)
	     	//告诉所有用户，目前聊天室有多少人
			io.emit('userList',users)
			socket.username = data.username
			socket.avatar = data.avatar
		}
	})
	
	socket.on('disconnect',()=>{
		//把当前用户的信息从users中删除掉
		//有人离开聊天室，userList发生更新
		let index = users.findIndex(item => item.username === socket.username)
		users.splice(index,1)//删除断开连接这个人
		io.emit('delUser',{
			username:socket.username,
			avatar:socket.avatar
		})
		// console.log(users)
		io.emit('userList',users)
	})
	//监听聊天的消息
	socket.on('sendMessage',data=>{
		// console.log(data);
		//广播给所有用户
		io.emit('receiveMessage',data)
	})
	//接收图片信息
	socket.on('sendImage',data=>{
		// console.log(data)
		io.emit('receiveImage',data)
	})
})